package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.util.IdGenerator;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdGenerator idGenerator;

    @Override
    public void save(Video video) {
        //补全参数
        video.setVid(idGenerator.nextId("video"));
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(video);
    }

    @Override
    public PageResult findVideoList(int page, int pagesize) {
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int)count,pagesize,pages,page,videoList);
    }

    @Override
    public void followUser(Long id, Long targetUserId) {
        //补全属性
        FollowUser followUser = new FollowUser();
        followUser.setUserId(id);
        followUser.setFollowUserId(targetUserId);
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(followUser);

 }

    @Override
    public void unFollowUser(Long id, Long targetUserId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(id).and("followUserId").is(targetUserId));
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public PageResult<Video> findVideoListByUid(Long uid, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(uid))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);


        return new PageResult<>((int) count, pagesize, pages, page, videoList);
    }

    @Override
    public Video findById(String videoId) {
       return mongoTemplate.findById(new ObjectId(videoId), Video.class);

    }


}
